//
//  PageContentView.swift
//  DouYuZB
//
//  Created by James on 2017/10/14.
//  Copyright © 2017年 James. All rights reserved.
//

import UIKit

private let cellId = "cellID"
private let collectionViewWidth = kScreenW

protocol PageContentViewDelegate :class{
    func pageContentView(pageContentView:PageContentView,progress:CGFloat,sourceIndex:Int,targetIndex:Int)
}

class PageContentView: UIView {
    fileprivate var childVCs: [UIViewController]
    fileprivate weak var parentVC: UIViewController?
    fileprivate var startOffsetX: CGFloat = 0
    weak var delegate:PageContentViewDelegate?
    fileprivate var isForbidScorllDelegate : Bool = false
    
    fileprivate lazy var collectionView: UICollectionView = {[weak self] in
        
        let layout = UICollectionViewFlowLayout()
        layout.itemSize = (self?.bounds.size)!
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        layout.scrollDirection = .horizontal
        
        let collectionView = UICollectionView(frame: (self?.bounds)!, collectionViewLayout: layout)
        collectionView.isPagingEnabled = true
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.bounces = false
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: cellId)
        
        return collectionView
    }()
    init(frame: CGRect,childVCs: [UIViewController],parentVC: UIViewController?) {
        self.childVCs = childVCs
        self.parentVC = parentVC
        super.init(frame: frame)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}
// MARK: - 设置UI界面
extension PageContentView {
    private func setupUI()  {
        //添加子控制器
        for childVC in childVCs {
            parentVC?.addChildViewController(childVC)
            childVC.view.frame = self.bounds
        }
        self.addSubview(collectionView)
    }
}
// MARK: - 代理
extension PageContentView : UICollectionViewDataSource{
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return childVCs.count
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath)
        
        //防止复用问题先做移除
        for view in cell.contentView.subviews {
            view.removeFromSuperview()
        }
        
        let vc = childVCs[indexPath.row]
        cell.contentView.addSubview(vc.view)
        
        return cell
    }
}

extension PageContentView : UICollectionViewDelegate {
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        isForbidScorllDelegate = false
        startOffsetX = scrollView.contentOffset.x
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        if isForbidScorllDelegate { return } //如果是点击事件就返回
        
        let offset = scrollView.contentOffset
        //1.定义获取需要的数据
        var progress:CGFloat = 0
        var sourceIndex:Int = Int(offset.x / collectionViewWidth)
        var targetIndex:Int = 0
        
        //2.判读滑动方向  计算偏移的百分比
        if offset.x > startOffsetX {//左滑
            progress = offset.x / collectionViewWidth - floor(offset.x / collectionViewWidth)
            //2.计算 sourceIndex  targetIndex

            targetIndex = sourceIndex + 1
            if(targetIndex >= childVCs.count - 1){
                targetIndex = childVCs.count - 1;
            }
            //如果完全划过一页
            if(offset.x - startOffsetX  == collectionViewWidth){
                progress = 1
                targetIndex = sourceIndex
            }
            
        }else{
            progress = 1 - (offset.x / collectionViewWidth - floor(offset.x / collectionViewWidth))
            
            targetIndex = sourceIndex
            sourceIndex = targetIndex + 1
            if(sourceIndex >= childVCs.count - 1){
                sourceIndex = childVCs.count - 1;
            }
        }
        
        //讲值传给代理
        delegate?.pageContentView(pageContentView: self, progress: progress, sourceIndex: sourceIndex, targetIndex: targetIndex)
    }
}
// MARK: - public
extension PageContentView {
    func setCurrentIndex(currentIndex:Int)  {
        //1.记录需要执行代理方法
        isForbidScorllDelegate = true
        
        //2.滚动
        let indexPath = IndexPath(item: currentIndex, section: 0)
        collectionView.scrollToItem(at:indexPath , at: .centeredHorizontally, animated: false)
    }
}
